<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class ForgetpasswdForm extends CFormModel
{
	public $email;	public $message;	public $enabledReigster;	public $enableMail;	private $_userId;	private $_userName;	public function init(){
		$this->enableMail = Yii::app()->params["app"]["enableMail"];
		$this->enabledReigster = Yii::app()->params["app"]["enabledReigster"];
		if($this->enableMail!="1"){			$this->addError("name", "系统不能发送邮件，请联系管理员");
		}
		 
	}
	public function rules()
	{
		return array(
		array('email', 'required'),
		array('email', 'email'),
		array('name', 'emailCheck'),
		);
	}
	
	public function emailCheck(){
		if(strlen($this->email)==0){
			return false;
		}
		$user = User::model()->find("id in(select user_id from ".Yii::app()->params['tablePrefix']."user_metas where meta_key='email' and meta_value=?)",array($this->email));
		if(!isset($user)){
			$this->addError("email", "电子邮件不存在，请检查");
			return false;
		}
		$this->_userName = $user["user_name"];
		$this->_userId = $user["id"];
		return true;
	}

	public function attributeLabels()
	{
		return array(
            'email'=>'电子邮件', 
		);
	}
	
	private function _getMailTitle(){
		$title = "[".Yii::app()->params['app']['name']."] 重置您的密码";
		return $title;
	}
	
	private function _getMailContent($passwd){
		$url = CSecurity::getForgetpasswdUrl($this->_userName);
		$body = "<div >有人要求重设如下帐号的密码：<br>
		<br>
		<a href=\"".Yii::app()->params['app']['host']."\" target=\"_blank\">".Yii::app()->params['app']['host']."</a><br>
		<br>
		用户名：".$this->_userName."<br>
		<br>
		若这不是您本人要求的，请忽略本邮件，一切如常。<br>
		<br>
		要重置您的密码，请打开下面的链接：<br>
		<br>&lt;<a href=\"".$url."\" target=\"_blank\">".$url."</a>&gt;<br>
		<br>
		</div></div>";
		return $body;
	}
	public function save(){
		if($this->validate()){
			$passwod = uniqid();
			$result = CEmailSender::sendMail($this->email, $this->_getMailTitle(), $this->_getMailContent($passwod));
			if($result==true){
								$meta = UserMeta::model()->find("user_id=? and meta_key='password_url_used'",array($this->_userId));
				if(!isset($meta)){
					$meta = new UserMeta();
					$meta["meta_key"]="password_url_used";
					$meta["user_id"]=$this->_userId;
				}
				$meta["meta_value"]="0";
				$meta->save();
				
				$this->message = "新密码重置方式已经发送，请查收我们给您发的邮件。";
			}else{
				$this->addError("email", $result);
			}
		}
	}

}
